﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PH.Model.Achievements;
using PH.Model.Standards;
namespace PH.Data.Statistics
{
    public class ArchiveCommand
    {
        public static void SaveCheck(DBCentre db, ArchiveModel model)
        {
            if (string.IsNullOrEmpty(model.Title))
                throw new Utils.PhException("请输入档案标题。");
        }

        public static ArchiveModel CreateNew(ArchiveModel model)
        {
            if (model != null)
            {
                using (DBCentre db = new DBCentre())
                {
                    SaveCheck(db, model);
                    var d = Convertor.ConvertFrom<Archive, ArchiveModel>(model);
                    //List<SchoolInArchive> ds=new List<SchoolInArchive>();
                    //if (d.AType == 2)
                    //{
                    //    var bureau = db.DataContext.Bureaus.FirstOrDefault(p => p.ID == d.BureauID);
                    //    var bs = Data.Systems.BureauCommand.GetChildren(bureau.Guid).Select(p => p.ID).ToList();
                    //    var ss = db.DataContext.Schools.Where(p => p.SchoolInBureaux.Any(o => bs.Contains(o.BureauID) || o.BureauID == bureau.ID)).ToList();
                    //    ss.ForEach(p =>
                    //    {
                    //        ds.Add(new SchoolInArchive()
                    //        {
                    //            ArchiveGuid = model.Guid,
                    //            SchoolGuid = p.Guid
                    //        });
                    //    });
                    //}
                    //else
                    //    ds = Convertor.ConvertFromCollection<SchoolInArchive, SchoolInArchiveModel>(model.JoinSchools);

                    //if (ds.Count==0)
                    //    throw new Utils.PhException("没有参与的学校。");

                    //d.SchoolInArchives = ds;
                    db.DataContext.Archives.Add(d);
                    db.DataContext.SaveChanges();
                    return model;
                }
            }
            return null;
        }

        public static void Update(ArchiveModel model)
        {
            if (model != null && model.Guid!=Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var d = db.DataContext.Archives.FirstOrDefault(p => p.Guid == model.Guid);
                    if (d != null)
                    {
                        SaveCheck(db, model);
                        //db.Delete<SchoolInArchive>(p => p.ArchiveGuid == model.Guid);
                        Convertor.UpdateValue(model, d);
                        
                        db.DataContext.SaveChanges();
                    }
                    else
                        throw new Utils.PhException("不存在的档案");
                }
            }
        }

        public static void Delete(Guid guid)
        {
            if (guid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    db.Delete<Archive>(p => p.Guid == guid);
                    db.DataContext.SaveChanges();
                }
            }
        }

        public static ArchiveModel GetModel(Guid guid)
        {
            if (guid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var d = db.DataContext.Archives.FirstOrDefault(p => p.Guid == guid);
                    if (d != null)
                    {
                        var ret = Convertor.ConvertTo<ArchiveModel, Archive>(d);
                        ret.JoinSchools = Convertor.ConvertCollection<SchoolInArchiveModel, SchoolInArchive, SchoolInArchiveCollection>(d.SchoolInArchives);
                        return ret;
                    }
                }
            }
            return null;
        }

        public static ArchiveCollection Gets(ArchiveQuery sea)
        {
            var ret = new ArchiveCollection();
            using (DBCentre db = new DBCentre())
            {
                IQueryable<Archive> q = db.DataContext.Archives;

                #region 条件查询
                if (sea != null)
                {
                    if (sea.AType == 1)
                        q = q.Where(p => p.SchoolID == sea.SchoolID);
                    else
                    {
                        if (sea.SchoolID > 0)
                        {
                            var dSchool = db.DataContext.Schools.FirstOrDefault(p => p.ID == sea.SchoolID);
                            if (dSchool != null)
                            {
                                var bs = dSchool.SchoolInBureaux.Select(p => p.BureauID).ToList();
                                q = q.Where(p => bs.Contains(p.BureauID.Value));
                            }
                            else
                                return ret;
                        }
                        else
                        {
                            var bureau = db.DataContext.Bureaus.FirstOrDefault(p => p.ID == sea.BureauID);
                            var bs = PH.Data.Systems.BureauCommand.GetParents(bureau.Guid).Select(p=>p.ID).ToList();
                            q = q.Where(p => p.BureauID == bureau.ID || bs.Contains(p.BureauID.Value));
                        }
                    }
                    if (!string.IsNullOrEmpty(sea.Key))
                        q = q.Where(p => p.Title.Contains(sea.Key));
                    if (sea.Expired != null)
                    {
                        if (!sea.Expired.Value)
                        {
                            //查询未过期的记录
                            q = q.Where(p => p.BeginTime != null && p.BeginTime.Value.CompareTo(DateTime.Now) <= 0);
                            q = q.Where(p => p.EndTime!= null && p.EndTime.Value.CompareTo(DateTime.Now) > 0);
                        }
                        else
                            q = q.Where(p =>  p.EndTime != null && p.EndTime.Value.CompareTo(DateTime.Now) <= 0);
                    }
                }
                #endregion

                var n = 0;
                q = q.OrderByDescending(p => p.CreatedOn);
                if (sea != null && sea.PageSize > 0)
                {
                    n = q.Count();
                    q = q.Skip(sea.PageSize * sea.PageIndex).Take(sea.PageSize);
                }

                var lst = q.ToList();
                ret = Convertor.ConvertCollection<ArchiveModel, Archive, ArchiveCollection>(lst);
                ret.TotalRecordsCount = n > 0 ? n : lst.Count;

                #region 辅助字段
                if (sea != null)
                {
                    if (sea.GetMarkCount)
                    {
                        ret.ForEach(p =>
                        {
                            var d = lst.Find(o => o.Guid == p.Guid);
                            p.MarkCount = d.Marks.Count();
                        });
                    }
                }
                #endregion
            }
            return ret;
        }

        public static ArchiveCollection GetArchives(ArchiveQuery sea)
        {
            var ret = new ArchiveCollection();
            if (sea != null)
            {
                using (DBCentre db = new DBCentre())
                {
                    var n = 0;
                    IQueryable<Archive> q = db.DataContext.Archives;
                    if (sea.SchoolGuid != Guid.Empty)
                    {
                        var school = db.DataContext.Schools.FirstOrDefault(p => p.Guid == sea.SchoolGuid);
                        if (school != null)
                        {
                            if (sea.AType == 1)
                                q = q.Where(p => p.SchoolID == school.ID);
                            else
                            {
                                var bs = school.SchoolInBureaux.Select(p => p.BureauID).ToList();
                                q = q.Where(p => bs.Contains(p.BureauID.Value));
                            }
                        }
                        else
                            return ret;
                    }
                    else if (sea.BureauGuid != Guid.Empty)
                    {
                        var bureau = db.DataContext.Bureaus.FirstOrDefault(p => p.Guid == sea.BureauGuid);
                        if (bureau != null)
                        {
                            var bs = PH.Data.Systems.BureauCommand.GetParents(bureau.Guid).Select(p => p.ID).ToList();
                            q = q.Where(p => p.BureauID == bureau.ID || bs.Contains(p.BureauID.Value));
                        }
                        else
                            return ret;
                    }
                    else
                        return ret;
                    
                    if (!string.IsNullOrEmpty(sea.Key))
                        q = q.Where(p => p.Title.Contains(sea.Key));
                    if (sea.Expired != null)
                    {
                        if (!sea.Expired.Value)
                        {
                            //查询未过期的记录
                            q = q.Where(p => p.BeginTime != null && p.BeginTime.Value.CompareTo(DateTime.Now) <= 0);
                            q = q.Where(p => p.EndTime != null && p.EndTime.Value.CompareTo(DateTime.Now) > 0);
                        }
                        else
                            q = q.Where(p => p.EndTime != null && p.EndTime.Value.CompareTo(DateTime.Now) <= 0);
                    }

                    q = q.OrderByDescending(p => p.CreatedOn);
                    if (sea != null && sea.PageSize > 0)
                    {
                        n = q.Count();
                        q = q.Skip(sea.PageSize * sea.PageIndex).Take(sea.PageSize);
                    }
                    var lst = q.ToList();
                    ret = Convertor.ConvertCollection<ArchiveModel, Archive, ArchiveCollection>(lst);
                    ret.TotalRecordsCount = n > 0 ? n : lst.Count;
                }
            }
            return ret;
        }

        public static ArchiveCollection GetMyArchives(ArchiveQuery sea)
        {
            var ret = new ArchiveCollection();
            using (DBCentre db = new DBCentre())
            {
                IQueryable<Archive> q = db.DataContext.Archives;
                q = q.Where(p => (p.SchoolID == sea.SchoolID && p.AType == 1) || (p.BureauID == sea.BureauID && p.AType == 2));
                if (sea != null)
                {
                    if (!string.IsNullOrEmpty(sea.Key))
                        q = q.Where(p => p.Title.Contains(sea.Key));
                }
                var n = q.Count();
                if (n > 0)
                {
                    q = q.OrderByDescending(p => p.CreatedOn);
                    if (sea != null && sea.PageSize > 0)
                        q = q.Skip(sea.PageSize * sea.PageIndex).Take(sea.PageSize);
                    var lst = q.ToList();
                    ret = Convertor.ConvertCollection<ArchiveModel, Archive, ArchiveCollection>(lst);
                    ret.TotalRecordsCount = n;

                    if (sea != null)
                    {
                        if (sea.GetMarkCount)
                        {
                            ret.ForEach(p =>
                            {
                                var d = lst.Find(o => o.Guid == p.Guid);
                                p.MarkCount = d.Marks.Count();
                            });
                        }
                    }
                }
            }
            return ret;
        }

        public static ArchiveCollection GetArchivesByStudent(int studentID)
        {
            ArchiveCollection ret = new ArchiveCollection();
            if (studentID > 0)
            {
                using (DBCentre db = new DBCentre())
                {
                    var q = db.DataContext.Archives.Where(p => p.Marks.Any(o => o.StudentID == studentID));
                    q = q.OrderByDescending(p => p.CreatedOn);
                    var lst = q.ToList();
                    ret = Convertor.ConvertCollection<ArchiveModel, Archive, ArchiveCollection>(lst);
                    ret.TotalRecordsCount = lst.Count();
                    var subjects = db.DataContext.Subjects.ToList();
                    ret.ForEach(p => {
                        var dmarks = db.DataContext.Marks.Where(o => o.ArchiveGuid == p.Guid && o.StudentID == studentID).ToList();
                        p.Marks = Convertor.ConvertCollection<MarkModel, Mark, MarkCollection>(dmarks);

                        p.Marks.ForEach(o => {
                            o.Subject = Convertor.ConvertTo<SubjectModel, Subject>(subjects.Find(r => r.ID == o.SubjectID));
                        });
                    });
                }
            }
            return ret;
        }
    }
}
